package org.timemanager.view;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.afree.chart.AFreeChart;
import org.afree.chart.ChartFactory;
import org.afree.chart.plot.PlotOrientation;
import org.afree.chart.plot.XYPlot;
import org.afree.chart.renderer.xy.XYItemRenderer;
import org.afree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.afree.data.xy.XYSeries;
import org.afree.data.xy.XYSeriesCollection;

import android.content.Context;
import android.database.Cursor;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;

/**
 * draw a event's trend chart
 * @author Dereky
 *
 */
public class EventTrendAnalyzeView extends DemoView {
	private DatabaseTool databaseTool;
	
	public EventTrendAnalyzeView(Context context, AttributeSet attrs) {
		super(context, attrs);
		databaseTool=new DatabaseTool(context);
	}

	public EventTrendAnalyzeView(Context context) {
		super(context);
		databaseTool=new DatabaseTool(context);
	}
	public void close(){
		try{
			databaseTool.close();
		}catch (Exception e) {
			// TODO: handle exception
		}
	}
	/**
	 * show a finished event's trend static chart during a month.
	 */
	public void showChart()
	{
		Calendar startCalendar=Calendar.getInstance();
		startCalendar.setTime(EventTrendAnalyzeActivity.curCalendar.getTime());
		Calendar endCalendar=Calendar.getInstance();
		endCalendar.setTime(startCalendar.getTime());
		endCalendar.add(Calendar.MONTH, 1);
		
		Map<Date, Integer> map=new HashMap<Date, Integer>();
		while(startCalendar.before(endCalendar)){
			Log.e("startCalendar",startCalendar.getTime().toString());
			map.put(startCalendar.getTime(), 0);
			startCalendar.add(Calendar.DAY_OF_MONTH, 1);
		}
		Log.e("startCalendar",startCalendar.getTime().toString());
		
		/*
		 * remember to reset start calendar since it increases every time
		 */
		startCalendar=Calendar.getInstance();
		startCalendar.setTime(EventTrendAnalyzeActivity.curCalendar.getTime());
		Date startDate=startCalendar.getTime();
		Date endDate=endCalendar.getTime();
		Cursor cursor=databaseTool.getMonthlyRecords(startDate, endDate, 
				EventTrendAnalyzeActivity.eventId);
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		while(cursor.moveToNext()){
			try{
				Date iEndDate=dateFormat.parse(cursor.getString(1));
				Date iStartDate=dateFormat.parse(cursor.getString(0));
				Log.e("cursor",iStartDate.toString()+"---"+iEndDate.toString());
				if(iStartDate.before(startDate)){
					iStartDate=startDate;
				}
				if(iEndDate.after(endDate)){
					iEndDate=endDate;
				}
				long duration = (iEndDate.getTime()-iStartDate.getTime())/60000;
				startCalendar.setTime(iStartDate);
				startCalendar.set(Calendar.HOUR_OF_DAY, 0);
				startCalendar.set(Calendar.MINUTE, 0);
				iStartDate=startCalendar.getTime();
				map.put(iStartDate, (int) (map.get(iStartDate)+duration));
			}
			catch (Exception e) {
				e.printStackTrace();
			}
		}
//		try{
//			cursor.close();
//		}catch (Exception e) {
//			// TODO: handle exception
//		}
		XYSeries series = new XYSeries("series", true, false);
		Iterator<Map.Entry<Date, Integer>> iterator=map.entrySet().iterator();
		while(iterator.hasNext()){
			Map.Entry<Date, Integer> entry=iterator.next();
			series.add(entry.getKey().getDate(), entry.getValue());
		}
		XYSeriesCollection xySC = new XYSeriesCollection();
    	xySC.addSeries(series);
    	
    	startCalendar=Calendar.getInstance();
		startCalendar.setTime(EventTrendAnalyzeActivity.curCalendar.getTime());
    	AFreeChart chart = ChartFactory.createXYLineChart(
    			new SimpleDateFormat(getResources().getText(R.string.event_trend_chart_title).toString()).
				format(startCalendar.getTime())+" "+
        		getResources().getText(R.string.event_trend_chart).toString(),
        		getResources().getText(R.string.event_trend_x_axis).toString(),
        		getResources().getText(R.string.event_trend_y_axis).toString(),
                xySC,
                PlotOrientation.VERTICAL,
                false,
                true,
                false);
    	
    	XYPlot plot = (XYPlot) chart.getPlot();
    	XYItemRenderer r = plot.getRenderer();
    	XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) r;
        renderer.setBaseShapesVisible(true);
        
    	setChart(chart);
	}
	
	private MotionEvent previousMotion;
	private boolean isMove;
	@Override
	public boolean onTouchEvent(MotionEvent ev) {
		switch(ev.getAction()){
			case MotionEvent.ACTION_DOWN:
				previousMotion=MotionEvent.obtain(ev);
				isMove=false;
				break;
			case MotionEvent.ACTION_MOVE:
				isMove=true;
				break;
			case MotionEvent.ACTION_UP:
				if(isMove && ev!=null && previousMotion!=null){
					Log.e("analyze x",(previousMotion.getRawX()-ev.getRawX())+"");
					Log.e("analyze y",(previousMotion.getRawY()-ev.getRawY())+"");
					if(Math.abs(previousMotion.getRawX()-ev.getRawX())>
						Math.abs(previousMotion.getRawY()-ev.getRawY()) && 
						Math.abs(previousMotion.getRawX()-ev.getRawX())>DailyAnalyzeView.DEFAULT_SLIDE_DISTANCE){
						if(previousMotion.getRawX()<ev.getRawX()){
							EventTrendAnalyzeActivity.curCalendar.add(Calendar.MONTH, -1);
							showChart();
						}else {
							EventTrendAnalyzeActivity.curCalendar.add(Calendar.MONTH, 1);
							if(EventTrendAnalyzeActivity.
									curCalendar.after(Calendar.getInstance())){
								EventTrendAnalyzeActivity.curCalendar.add(Calendar.MONTH, -1);
//								Toast.makeText(EventTrendAnalyzeActivity.this, 
//										getText(R.string.event_trend_over_last), Toast.LENGTH_SHORT).show();
							}
							else{
								showChart();
							}
						}
						
					}
					isMove=false;
					previousMotion=null;
					/*
					 * when it detects horizontal scroll gesture,
					 * then there is no need to pass to super to handle 
					 */
					return true;
				}
				break;
		}
		
		return true;
		//return super.onTouchEvent(ev);
	}
}
